// components/add-plate/input.ts
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    value: {
      type: String
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    range: ["燃油车", "新能源车"],
    // 下拉框选项索引
    index: 0,
    // 输入框索引
    inputIndex: 0,
    inputs: new Array<string>(7),
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 点击选择车牌类型
    bindPickerChange(e: WechatMiniprogram.PickerChange) {
      let index = <number><any>e.detail.value;
      let inputs: Array<string> = this.data.inputs;
      if (index == 0) {
        inputs.length = 7;
      } else {
        inputs.length = 8;
      }
      this.setData({
        index,
        inputs
      })
    },
    // 点击输入框
    handleTap(e: WechatMiniprogram.BaseEvent) {
      let inputIndex = <number><any>e.currentTarget.dataset.index;
      this.setData({ inputIndex })
      this.triggerEvent("indexChange", inputIndex);
    },
    // 点击按钮
    handleAdd() {
      let inputs: Array<string> = this.data.inputs;
      let empty = inputs.some(v => v == null);
      // 有空的值
      if (empty) {
        return;
      }
      let result = inputs.join("");
      // 异步发送请求(调用接口)
      setTimeout(() => {
        console.log("提交成功：", result);
        this.triggerEvent("addSuccess", result);
      }, 100)
    }
  },
  observers: {
    "value": function (val) {
      if (val) {
        let inputs: Array<string> = this.data.inputs;
        let inputIndex = this.data.inputIndex;
        inputs[inputIndex] = val;
        if (inputIndex < inputs.length - 1) {
          inputIndex++;
        }

        // 使用响应键盘的索引
        let keyIndex = inputIndex;
        if (keyIndex == inputs.length - 1) {
          keyIndex = 3;
        } else if (keyIndex > 2) {
          keyIndex = 2;
        }
        if (inputIndex <= inputs.length - 1) {
          this.triggerEvent("keyChange", keyIndex);
        }
        this.setData({ inputs, inputIndex })
      }
    }
  }
})
